home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 4769 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.1 KB

  1. Path: mail2news.demon.co.uk!genesis.demon.co.uk
  2. From: Lawrence Kirby <fred@genesis.demon.co.uk>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: random number
  5. Date: Tue, 06 Feb 96 20:03:59 GMT
  6. Organization: none
  7. Message-ID: <823637039snz@genesis.demon.co.uk>
  8. References: <3115D5B3.41C6@bazis.nl>
  9. Reply-To: fred@genesis.demon.co.uk
  10. X-NNTP-Posting-Host: genesis.demon.co.uk
  11. X-Newsreader: Demon Internet Simple News v1.27
  12. X-Mail2News-Path: genesis.demon.co.uk
  13.  
  14. In article <3115D5B3.41C6@bazis.nl> fkorntne@bazis.nl "Franz Korntner" writes:
  15.  
  16. >> >Hi,
  17. >> >Could anybody help me to generate some code to produce
  18. >> >a random number between -3 and 3 ?
  19. >> >I'm trying to use rand(), but since it doesn't receive
  20. >> 
  21. >> Each time you call rand map the result into the interval -3 ... 3.
  22. >> You can do this, for example, as follows:
  23. >> 
  24. >>    r = (rand() % 7) - 3;
  25. >> 
  26. >> If you are using rand be sure and read about the role of srand
  27. >> in "initializing" the sequence of random numbers that are generated.
  28. >
  29. >You are using rand()%7 to get a number in the range 0..7 but this method is
  30. >incorrect. Performing operations on random numbers is okay as long as all
  31. >bits of the number are included in the operation.
  32.  
  33. Actually in this case they are (since 7 is odd)! :-)
  34.  
  35. It is a bad approach in general though.
  36.  
  37. >It is known to be
  38. >dangerous to extract bits from a pseudo-random number and assume that those
  39. >bits have random properties. Even worse, it is also known that the less
  40. >significant bits of some random number generators are not random at all! In
  41. >this case you are selecting the 3 most less significant bits of the number,
  42. >the worst choice that could have been made.
  43.  
  44. (rand() & 7) or (rand() % 8) would do as you say and be a bad thing.
  45.  
  46.  A better solution is to use the
  47. >magnitude of the random number, but such operations are implemention
  48. >dependent (overflows, and such) as in:
  49. >  (rand()*7)/(MAXRAND+1)
  50.  
  51. The FAQ contains better approaches.
  52.  
  53. -- 
  54. -----------------------------------------
  55. Lawrence Kirby | fred@genesis.demon.co.uk
  56. Wilts, England | 70734.126@compuserve.com
  57. -----------------------------------------
  58.